/*
 *  Copyright 2001-2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package ar.uba.fi.posgrado.economy.service.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import ar.uba.fi.posgrado.academy.model.Teacher;
import ar.uba.fi.posgrado.common.dao.DAOException;
import ar.uba.fi.posgrado.common.dao.NoSuchEntityException;
import ar.uba.fi.posgrado.common.exception.PosgradoException;
import ar.uba.fi.posgrado.common.exception.PosgradoRuntimeException;
import ar.uba.fi.posgrado.common.exception.RepeatedInstanceException;
import ar.uba.fi.posgrado.common.exception.RepeatedNameException;
import ar.uba.fi.posgrado.common.model.User;
import ar.uba.fi.posgrado.economy.dao.ProviderAccountDAO;
import ar.uba.fi.posgrado.economy.exception.AccountRuleException;
import ar.uba.fi.posgrado.economy.model.ProviderAccount;
import ar.uba.fi.posgrado.economy.service.ProviderAccountService;

/**
 * Servicio concreto para cuentas corrientes de docentes (proveedores).<br>
 * 
 * @author pablo.tortorella
 * @see ProviderAccountService
 */
public class ProviderAccountServiceImpl implements ProviderAccountService {

	/** Logger */
	private static Logger logger = Logger
			.getLogger(ProviderAccountServiceImpl.class);

	private ProviderAccountDAO providerAccountDAO;

	/**
	 * 
	 * @return el dao de cuentas corrientes
	 */
	public ProviderAccountDAO getProviderAccountDAO() {
		return this.providerAccountDAO;
	}

	/**
	 * 
	 * @param providerAccountDAO
	 */
	public void setProviderAccountDAO(ProviderAccountDAO providerAccountDAO) {
		this.providerAccountDAO = providerAccountDAO;
	}

	public ProviderAccountServiceImpl() {

	}

	/**
	 * Constructor para prueba unitaria
	 * 
	 * @param providerAccountDAO
	 */
	public ProviderAccountServiceImpl(ProviderAccountDAO providerAccountDAO) {
		this.setProviderAccountDAO(providerAccountDAO);
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public void create(ProviderAccount providerAccount)
			throws PosgradoRuntimeException, PosgradoException,
			RepeatedInstanceException, AccountRuleException {
		if ((providerAccount.getTotalDebt().compareTo(new Double(0)) != 0)) {
			throw new AccountRuleException(
					"No se pueden crear Cuentas Corrientes con saldo positivo, ni con deudas");
		}
		try {
			this.getProviderAccountDAO().save(providerAccount);
			logger.info("Cuenta Corriente del docente: "
					+ providerAccount.getProvider().getName()
					+ " creada con exito");
		} catch (DAOException e) {
			throw new PosgradoException(
					"Excepcion al crear la cuenta corriente del docente: "
							+ providerAccount.getProvider().getName(), e);
		}
	}

	public ProviderAccount getByTeacherId(Long teacherId)
			throws PosgradoRuntimeException, PosgradoException {
		return this.getProviderAccountDAO().findByTeacherId(teacherId);
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public ProviderAccount update(ProviderAccount providerAccount)
			throws PosgradoRuntimeException, PosgradoException,
			NoSuchEntityException, RepeatedNameException {

		if (providerAccount.getTotalDebt().compareTo(new Double(0)) > 0) {
			String mensaje = "No se pueden crear Cuentas Corrientes con saldo positivo, ni con deudas";
			AccountRuleException e = new AccountRuleException(mensaje);
			throw e;
		}
		ProviderAccount toUpdateAccount = this.getById(providerAccount.getId());
		toUpdateAccount.setTotalDebt(providerAccount.getTotalDebt());

		providerAccount = this.update(toUpdateAccount);
		return providerAccount;
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public void delete(ProviderAccount providerAccount)
			throws PosgradoRuntimeException, PosgradoException {
		try {
			ProviderAccount providerAccountToDelete = this
					.getById(providerAccount.getId());
			this.getProviderAccountDAO().remove(providerAccountToDelete);
		} catch (NoSuchEntityException e) {
			throw new PosgradoException(
					"Error al borrar cta cte. No se encontro ninguna cuenta con id '"
							+ providerAccount.getId() + "' en el sistema", e);
		}
	}

	public List<ProviderAccount> getAll() throws PosgradoRuntimeException,
			PosgradoException {
		List<ProviderAccount> providerAccounts = null;
		try {
			providerAccounts = this.getProviderAccountDAO().findAll();
		} catch (DAOException e) {
			throw new PosgradoException(
					"Ocurrio un error al obtener todas las ctas ctes", e);
		}
		return providerAccounts;
	}

	public ProviderAccount getById(Long id) throws PosgradoRuntimeException,
			PosgradoException {
		ProviderAccount providerAccount = null;
		try {
			providerAccount = (ProviderAccount) this.getProviderAccountDAO()
					.findById(id);
		} catch (DAOException e) {
			throw new PosgradoException("Ocurrio un error al obtener "
					+ "la cuenta con Id " + id, e);
		}
		return providerAccount;
	}

	public Teacher getProviderByAccountId(Long accountId)
			throws PosgradoRuntimeException, PosgradoException {
		Teacher teacher = null;
		try {
			ProviderAccount account = this.getById(accountId);
			teacher = account.getProvider();
		} catch (DAOException e) {
			throw new PosgradoException("Ocurrio un error al obtener "
					+ "el docente de la cuenta con Id " + accountId, e);
		}
		return teacher;
	}

	/** 
	 * @see ar.uba.fi.posgrado.common.service.GenericService#filter(java.util.List, ar.uba.fi.posgrado.common.model.User)
	 */
	public List<ProviderAccount> filter(List<ProviderAccount> list, User user)
			throws PosgradoRuntimeException, PosgradoException {
		return list;
	}

	
	
}
